package com.smart.community.commons.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 服务健康检查监控服务
 * 
 * 定期检查各个服务的健康状态
 * 记录服务可用性指标，提供监控数据
 * 
 * @author Wu.Liang
 * @version 2.0.0
 * @since 2025-08-28
 */
@Slf4j
@Service
public class ServiceHealthMonitor {
    
    /**
     * 服务健康状态缓存
     * key: 服务名称
     * value: 健康状态信息
     */
    private static final ConcurrentHashMap<String, HealthStatus> healthStatusMap = new ConcurrentHashMap<>();
    
    /**
     * 每30秒检查一次服务健康状态
     */
    @Scheduled(fixedRate = 30000)
    public void checkServiceHealth() {
        try {
            log.debug("开始检查服务健康状态");
            
            // 检查停车服务健康状态
            checkParkingServiceHealth();
            
            // 可以添加其他服务的健康检查
            // checkUserServiceHealth();
            // checkPropertyServiceHealth();
            
            log.debug("服务健康状态检查完成");
        } catch (Exception e) {
            log.error("服务健康状态检查失败", e);
        }
    }
    
    /**
     * 检查停车服务健康状态
     */
    private void checkParkingServiceHealth() {
        String serviceName = "停车服务";
        
        try {
            // 模拟健康检查，实际项目中应该调用具体的健康检查接口
            boolean isHealthy = Math.random() > 0.1; // 90%的成功率
            
            HealthStatus healthStatus = new HealthStatus();
            healthStatus.setServiceName(serviceName);
            healthStatus.setHealthy(isHealthy);
            healthStatus.setLastCheckTime(System.currentTimeMillis());
            
            if (isHealthy) {
                healthStatus.setConsecutiveFailures(0);
                log.debug("{}健康状态检查通过", serviceName);
            } else {
                healthStatus.incrementFailures();
                log.warn("{}健康状态检查失败，连续失败次数: {}", serviceName, healthStatus.getConsecutiveFailures());
            }
            
            healthStatusMap.put(serviceName, healthStatus);
            
        } catch (Exception e) {
            HealthStatus healthStatus = healthStatusMap.getOrDefault(serviceName, new HealthStatus());
            healthStatus.setServiceName(serviceName);
            healthStatus.setHealthy(false);
            healthStatus.setLastCheckTime(System.currentTimeMillis());
            healthStatus.setErrorMessage(e.getMessage());
            healthStatus.incrementFailures();
            
            healthStatusMap.put(serviceName, healthStatus);
            
            log.warn("{}健康状态检查异常，连续失败次数: {}, 错误: {}", 
                    serviceName, healthStatus.getConsecutiveFailures(), e.getMessage());
        }
    }
    
    /**
     * 获取服务健康状态
     * 
     * @param serviceName 服务名称
     * @return 健康状态
     */
    public HealthStatus getHealthStatus(String serviceName) {
        return healthStatusMap.get(serviceName);
    }
    
    /**
     * 获取所有服务健康状态
     * 
     * @return 所有服务健康状态
     */
    public Map<String, HealthStatus> getAllHealthStatus() {
        return healthStatusMap;
    }
    
    /**
     * 检查服务是否健康
     * 
     * @param serviceName 服务名称
     * @return 是否健康
     */
    public boolean isServiceHealthy(String serviceName) {
        HealthStatus status = healthStatusMap.get(serviceName);
        return status != null && status.isHealthy();
    }
    
    /**
     * 获取服务连续失败次数
     * 
     * @param serviceName 服务名称
     * @return 连续失败次数
     */
    public int getConsecutiveFailures(String serviceName) {
        HealthStatus status = healthStatusMap.get(serviceName);
        return status != null ? status.getConsecutiveFailures() : 0;
    }
    
    /**
     * 健康状态信息类
     */
    public static class HealthStatus {
        private String serviceName;
        private boolean healthy;
        private long lastCheckTime;
        private String errorMessage;
        private Map<String, Object> serviceInfo;
        private final AtomicInteger consecutiveFailures = new AtomicInteger(0);
        
        public String getServiceName() {
            return serviceName;
        }
        
        public void setServiceName(String serviceName) {
            this.serviceName = serviceName;
        }
        
        public boolean isHealthy() {
            return healthy;
        }
        
        public void setHealthy(boolean healthy) {
            this.healthy = healthy;
        }
        
        public long getLastCheckTime() {
            return lastCheckTime;
        }
        
        public void setLastCheckTime(long lastCheckTime) {
            this.lastCheckTime = lastCheckTime;
        }
        
        public String getErrorMessage() {
            return errorMessage;
        }
        
        public void setErrorMessage(String errorMessage) {
            this.errorMessage = errorMessage;
        }
        
        public Map<String, Object> getServiceInfo() {
            return serviceInfo;
        }
        
        public void setServiceInfo(Map<String, Object> serviceInfo) {
            this.serviceInfo = serviceInfo;
        }
        
        public int getConsecutiveFailures() {
            return consecutiveFailures.get();
        }
        
        public void setConsecutiveFailures(int failures) {
            consecutiveFailures.set(failures);
        }
        
        public void incrementFailures() {
            consecutiveFailures.incrementAndGet();
        }
        
        public void resetFailures() {
            consecutiveFailures.set(0);
        }
        
        @Override
        public String toString() {
            return String.format("HealthStatus{serviceName='%s', healthy=%s, lastCheckTime=%d, consecutiveFailures=%d}", 
                    serviceName, healthy, lastCheckTime, consecutiveFailures.get());
        }
    }
}
